package com.hmusic.mymusic.controller;

import com.alibaba.fastjson.JSONObject;
import com.hmusic.mymusic.domain.Consumer;
import com.hmusic.mymusic.domain.EmailCode;
import com.hmusic.mymusic.service.ConsumerService;
import com.hmusic.mymusic.service.MsmService;
import com.hmusic.mymusic.utils.CodeUtil;
import com.hmusic.mymusic.utils.Consts;
import com.hmusic.mymusic.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
@Slf4j
@RequestMapping("/email")
public class EmailTestController {

    @Autowired
    private MsmService msmService;
    @Autowired
    private ConsumerService consumerService;
    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/send/{email}")
    @ResponseBody
    public Object send(@PathVariable String email){
        JSONObject jsonObject = new JSONObject();
        Consumer consumer = consumerService.oneConsumerByEmailCode(email);
        if (consumer != null){
            jsonObject.put(Consts.CODE,0);
            jsonObject.put(Consts.MSG,"邮箱已被注册");
            return jsonObject;
        }else {
            String code = (String) redisUtil.get(email);
            System.out.println(code);
            if (code!=null){
                jsonObject.put(Consts.CODE,0);
                jsonObject.put(Consts.MSG,"验证码已经发送过！");
                return jsonObject;
            }
            code = CodeUtil.getCode();
            msmService.sendEmail(email,code);
            redisUtil.set(email,code,60*5);
            jsonObject.put(Consts.CODE,1);
            jsonObject.put(Consts.MSG,"发送成功");
            return jsonObject;
        }

    }

    @PostMapping("/check")
    public Object checkCode(@RequestBody EmailCode emailCode){
        JSONObject jsonObject = new JSONObject();
        String code = (String) redisUtil.get(emailCode.getEmail());
        if (code!=null){
            if (code.equals(emailCode.getCode())){
                jsonObject.put(Consts.CODE,1);
                jsonObject.put(Consts.MSG,"注册成功");
                return jsonObject;
            }
        }else {
            jsonObject.put(Consts.CODE,0);
            jsonObject.put(Consts.MSG,"邮箱错误");
            return jsonObject;
        }
        return jsonObject;
    }
}
